package com.zzh.partnersys.im.rocketmq.producer;

import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @author zzh
 * @version 1.0
 * ������Ϣ�Ľӿ�rocketMQ
 */
@Component
public class MessageSender {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * ��ͬtopic�����Ͳ�ͬ���͵���Ϣ
     * @param topic
     * @param body
     */
    public void sendMsg(String topic, Object body) {
        final int[] retryCount = {0};
        final int maxRetryCount = 3; // ����������Դ�??

        Message<Object> build = MessageBuilder.withPayload(body).build();
        //�첽����??
        rocketMQTemplate.asyncSend(topic, build, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                //���ͳɹ�
                System.out.println("���ͳɹ�"+sendResult);
            }
            @Override
            public void onException(Throwable throwable) {
                //�쳣���������
                if (retryCount[0] < maxRetryCount) {
                    retryCount[0]++;
                    // ��������
                    sendMsg(topic, build);
                } else {
                    // �ﵽ������Դ�����Ĵ����߼�
                    // ���Լ�¼��־�����͸澯��
                }
            }
        });
    }
}
